//
//  LFPictureVIew.swift
//  SDAutoWeibo
//
//  Created by 刘健 on 16/3/26.
//  Copyright © 2016年 Clemmie. All rights reserved.
//

import UIKit
import SDWebImage
class LFPictureView: UICollectionView {
    
    // MARK: - 属性
    var picURLs: [NSURL]? {
        didSet {
            
            let size = setupCellFrame()
            
            //更新contentView 布局
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            
            //当拿到pictureURLs后.来根据pictureURLs的数量重新设置collectionView
            self.reloadData()
        }
    }
    
    func setupCellFrame() -> CGSize {
        
        //默认尺寸
        layout.itemSize = CGSize(width: LFCollectionCellWH, height: LFCollectionCellWH)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        let count = picURLs?.count ?? 0
        
        if count == 0 {
            
            //            layout.itemSize = CGSizeZero
            return CGSizeZero
        }
        
        //获取缓存里面的图片大小
        if count == 1 {
            //默认值
            layout.itemSize = CGSize(width: 160, height: 120)
            
            //从缓存里面找图片
            let picURLString = picURLs![0].absoluteString
            if let cacheImage = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(picURLString) {
                
                layout.itemSize = cacheImage.size
            }
            
            //处理照片宽度
            // 有些图片太小了
            if layout.itemSize.width < 40 {
                layout.itemSize.width = 40
            }
            
            // 图片太大
            if layout.itemSize.width > UIScreen.mainScreen().bounds.width * 0.5 {
                layout.itemSize.width = UIScreen.mainScreen().bounds.width * 0.5
            }
        
            return layout.itemSize
        }
        
        //多个图 处理
        
        layout.minimumInteritemSpacing = LFSpaceMargin
        layout.minimumLineSpacing = LFSpaceMargin
        
        var MaxCount = LFMAXCellCount
        
        
        if count == 2 || count == 4 {
            MaxCount = 2
        }
        
        let row = (count + MaxCount - 1 ) / MaxCount
        
        let width = LFCollectionCellWH * CGFloat(MaxCount) + (CGFloat(MaxCount) - 1) * LFSpaceMargin
        
        // 计算高度 cell的高度 * 行数 + (行数 - 1) * cell之间的间距
        let height = LFCollectionCellWH * CGFloat(row) + (CGFloat(row) - 1) * LFSpaceMargin
        
        return CGSize(width: width, height: height)
        
    }
    
    private let ReuseIdentifier = "ReuseIdentifier"
    /// 布局
    private let layout = UICollectionViewFlowLayout()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        self.dataSource = self
        self.registerClass(LFPictureCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
        
        self.backgroundColor = UIColor.clearColor()
        
    }
}


//MARK: --UICollectionViewDataSource {
extension LFPictureView: UICollectionViewDataSource {
    
    //根据图片url设置组数
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView .dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! LFPictureCell
        
        cell.thumbnailPicURL = picURLs?[indexPath.item]
        
        //        print("\(cell.thumbnailPicURL)")
        
        return cell
    }
}

class LFPictureCell: UICollectionViewCell {
    
    //MARK: -- 图片的URL属性
    var thumbnailPicURL: NSURL? {
        didSet {
            
            //下载图片
            if let url = thumbnailPicURL {
                
                picImageView.sd_setImageWithURL(url)
                
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareUI()
    }
    
    //MARK: --  UI布局
    private func prepareUI() {
        
        contentView.addSubview(picImageView)
        
        picImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        
        picImageView.contentMode = UIViewContentMode.ScaleAspectFill
        
        picImageView.clipsToBounds = true
        
    }
    
    //MARK: -- 懒加载
    private lazy var picImageView: UIImageView = UIImageView()

}

